//
//  CardAddModifyViewController.swift
//  NewCard
//
//  Created by yihui on 2017/11/17.
//  Copyright © 2017年 yihui. All rights reserved.
//

import UIKit

enum setupDataType {
    case Add
    case Edit
}

class CardAddModifyViewController: UIViewController {

    //MARK: -- 控件属性
    @IBOutlet weak var addCardButton: UIButton!
    // 容器view
    @IBOutlet weak var contectView: UIView!
    // 银行名称
    @IBOutlet weak var bankNameField: UITextField!
    // 银行卡号
    @IBOutlet weak var bankCardField: UITextField!
    // 固定额度
    @IBOutlet weak var totalField: UITextField!
    // 临时额度
    @IBOutlet weak var temporaryAmountField: UITextField!
    // 可用额度
    @IBOutlet weak var usableAmountField: UITextField!
    // 账单日
    fileprivate lazy var billDateField : UITextField = {
        let w : CGFloat = 200
        let h : CGFloat = 25
        let x : CGFloat = (UIScreen.main.bounds.width - w) * 0.5
        let y : CGFloat = self.usableAmountField.bottom + 10
        let billDateField = PickerTextField(frame: CGRect(x: x, y: y, width: w, height: h),
                                            placeholder: "账单日")
        billDateField.delegate = self
        return billDateField
    }()
    // 还款日
    fileprivate lazy var returnDateField : UITextField = {
        let w : CGFloat = 200
        let h : CGFloat = 25
        let x : CGFloat = (UIScreen.main.bounds.width - w) * 0.5
        let y : CGFloat = self.billDateField.bottom + 10
        let returnDateField = PickerTextField(frame: CGRect(x: x, y: y, width: w, height: h),
                                              placeholder: "还款日")
        returnDateField.delegate = self
        return returnDateField
    }()
    // 确认按钮
    @IBOutlet weak var enterButton: UIButton!
    
    // 存储 UITextField 的 frame
    fileprivate var textFieldFrame : CGRect!
    
    // 接收页面模式
    var isEdit : Bool = false
    // 接收数据模型
    var model : CardModel!

    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
        
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
        //HHLog("销毁")
    }
}

extension CardAddModifyViewController {
    
    fileprivate func setupUI() {
        
        setupTextFieldDalegate()
        setupNotification()
        
        view.addSubview(returnDateField)
        view.addSubview(billDateField)
        addCardButton.layer.cornerRadius = 10
        
        if isEdit {
            enterButton.setTitle("修改银行卡信息", for: .normal)
            bankNameField.text = model.bankName
            bankCardField.text = String(model.bankCard)
            bankNameField.isUserInteractionEnabled = false
            bankCardField.isUserInteractionEnabled = false
            totalField.text = String(model.total)
            temporaryAmountField.text = String(model.temporaryAmount)
            usableAmountField.text = String(model.usableAmount)
            billDateField.text = String(model.billDate)
            returnDateField.text = String(model.returnDate)
            enterButton.tag = 1
        }
    }
}

//MARK: -- 键盘和UITextField代理
extension CardAddModifyViewController : UITextFieldDelegate {
    
    // 通知
    fileprivate func setupNotification() {
        // 键盘监听通知
        NotificationCenter.default.addObserver(self, selector: #selector(self.kbFrameChanged(_:)), name: .UIKeyboardWillChangeFrame, object: nil)
    }
    
    fileprivate func setupTextFieldDalegate() {
        
        bankNameField.delegate = self
        bankCardField.delegate = self
        totalField.delegate = self
        temporaryAmountField.delegate = self
        usableAmountField.delegate = self
        billDateField.delegate = self
        returnDateField.delegate = self
        
    }
    //MARK: -- 获取当前被选择的UITextField
    func textFieldDidBeginEditing(_ textField: UITextField) {
        textFieldFrame = textField.frame
    }
    
    //MARK: -- Return 关闭键盘
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        
        textField.resignFirstResponder()
        
        return true
    }
    //MARK: --<#name> 弹出键盘上移UI
    @objc fileprivate func kbFrameChanged( _ notification : Notification) {
        
        let info = notification.userInfo
        let kbRect = (info?[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        let bottomSpacing: CGFloat = 50
        let maxY = view.frame.height - (textFieldFrame.maxY + bottomSpacing)
        let offset : CGFloat = maxY - kbRect.height
        let offsetY : CGFloat = (kbRect.origin.y < view.frame.height) ? offset : 0
        if (kbRect.height) > (view.bounds.height-textFieldFrame.maxY-bottomSpacing) {
            UIView.animate(withDuration: 0.3) {
                self.contectView.transform = CGAffineTransform(translationX: 0, y: offsetY)
            }
        }
    }
    //MARK: -- 关闭空白处关闭键盘
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        view.endEditing(true)
    }
}



//MARK: -- 点击事件
extension CardAddModifyViewController {
    
    @IBAction func cardAddModifyBtnClick(_ sender: UIButton) {
        if sender.tag == 0 {
            
            guard setupData(type: .Add) else {
                return
            }
        } else if sender.tag == 1 {
            
            guard setupData(type: .Edit) else {
                return
            }
        }
        
        self.navigationController?.popViewController(animated: true)
    }
}

//MARK: -- 数据处理
extension CardAddModifyViewController {
    
    fileprivate func setupData(type : setupDataType) -> Bool {
       
        guard let name = bankNameField.text,
                  bankNameField.text != "",
              let card = bankCardField.text,
                  bankCardField.text != "",
              let total = totalField.text,
                  totalField.text != "",
              let temporaryAmount = temporaryAmountField.text,
                  temporaryAmountField.text != "",
              let usableAmount = usableAmountField.text,
                  usableAmountField.text != "",
              let billDate = billDateField.text,
                  billDateField.text != "",
              let returnData = returnDateField.text,
                  returnDateField.text != ""
            else {
            Tools.show(self, message: "请填写完整信息")
            return false
        }

        
        //HHLog("\(name),\(card),\(total),\(temporaryAmount),\(usableAmount),\(billDate),\(returnData)")
        
        let data = CardModel()
        data.bankName = name
        data.bankCard = Int(card)!
        data.total = Double(total)!
        data.temporaryAmount = Double(temporaryAmount)!
        data.usableAmount = Double(usableAmount)!
        data.billDate = Int(billDate)!
        data.returnDate = Int(returnData)!
        
        var isOK : Bool = false
        
        switch type {
        case .Add:
            isOK = OpenData.insertData(data: data)
        case .Edit:
            data.id = model.id
            isOK = OpenData.updateData(data: data)
        }
        
        
        return isOK
        
    }
    

}
